// 文档加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 表单验证功能
    setupFormValidations();

    // 设置按钮交互效果
    setupButtonInteractions();

    // 设置表格行悬停效果
    setupTableHoverEffects();

    // 设置平滑滚动
    setupSmoothScroll();

    // 为导航栏设置当前活动项
    setActiveNavItem();

    // 搜索表单重置功能增强
    enhanceSearchForm();

    // 添加工具提示功能
    addTooltips();

    // 添加表单输入动画
    setupFormInputAnimations();

    // 添加页面元素进入动画
    setupElementAnimations();
});

// 表单验证功能
function setupFormValidations() {
    // 登录表单验证
    const loginForm = document.querySelector('form[action*="/login"]');
    if (loginForm) {
        loginForm.addEventListener('submit', function(e) {
            const username = this.querySelector('input[name="username"]').value;
            const password = this.querySelector('input[name="password"]').value;

            if (!username || !password) {
                e.preventDefault();
                showNotification('请输入用户名和密码', 'error');
            }
        });
    }

    // 员工表单验证（添加和编辑共用）
    const employeeForms = document.querySelectorAll('form[action*="/save"], form[action*="/update"]');
    employeeForms.forEach(form => {
        form.addEventListener('submit', function(e) {
            let isValid = true;
            let errorMessages = [];

            // 验证必填字段
            const requiredFields = this.querySelectorAll('[required]');
            requiredFields.forEach(field => {
                if (!field.value.trim()) {
                    isValid = false;
                    const label = this.querySelector(`label[for="${field.id}"]`);
                    const fieldName = label ? label.textContent.replace(' *', '') : field.name;
                    errorMessages.push(`${fieldName}不能为空`);
                    highlightError(field);
                } else {
                    removeHighlight(field);
                }
            });

            // 验证邮箱格式
            const emailField = this.querySelector('input[name="email"]');
            if (emailField && emailField.value.trim()) {
                const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if (!emailPattern.test(emailField.value)) {
                    isValid = false;
                    errorMessages.push('请输入有效的邮箱地址');
                    highlightError(emailField);
                } else {
                    removeHighlight(emailField);
                }
            }

            // 验证薪资格式
            const salaryField = this.querySelector('input[name="salary"]');
            if (salaryField && salaryField.value.trim()) {
                if (isNaN(salaryField.value) || parseFloat(salaryField.value) < 0) {
                    isValid = false;
                    errorMessages.push('请输入有效的薪资数字');
                    highlightError(salaryField);
                } else {
                    removeHighlight(salaryField);
                }
            }

            // 验证日期
            const dateField = this.querySelector('input[name="hireDate"]');
            if (dateField && dateField.value.trim()) {
                const selectedDate = new Date(dateField.value);
                const today = new Date();
                if (selectedDate > today) {
                    isValid = false;
                    errorMessages.push('入职日期不能晚于今天');
                    highlightError(dateField);
                } else {
                    removeHighlight(dateField);
                }
            }

            if (!isValid) {
                e.preventDefault();
                showNotification(errorMessages.join('\n'), 'error');
            } else {
                // 添加表单提交加载状态
                const submitButton = this.querySelector('.btn-submit, .btn-login');
                if (submitButton) {
                    const originalText = submitButton.textContent;
                    submitButton.textContent = '提交中...';
                    submitButton.disabled = true;
                    submitButton.classList.add('loading');

                    // 模拟表单提交延迟
                    setTimeout(() => {
                        this.submit();
                    }, 500);
                }
            }
        });
    });

    // 添加实时验证事件
    const formInputs = document.querySelectorAll('input, select');
    formInputs.forEach(input => {
        input.addEventListener('blur', function() {
            if (this.hasAttribute('required') && !this.value.trim()) {
                highlightError(this);
            } else {
                removeHighlight(this);
            }
        });
    });
}

// 高亮错误字段
function highlightError(element) {
    element.classList.add('error');
    element.style.animation = 'shake 0.5s ease-in-out';
    setTimeout(() => {
        element.style.animation = '';
    }, 500);
}

// 移除高亮
function removeHighlight(element) {
    element.classList.remove('error');
}

// 显示通知
function showNotification(message, type = 'info') {
    // 检查是否已存在通知元素
    let notification = document.querySelector('.custom-notification');
    if (notification) {
        document.body.removeChild(notification);
    }

    // 创建新通知元素
    notification = document.createElement('div');
    notification.className = `custom-notification ${type}`;
    notification.textContent = message;

    // 添加到页面
    document.body.appendChild(notification);

    // 显示动画
    setTimeout(() => {
        notification.style.opacity = '1';
        notification.style.transform = 'translateY(0)';
    }, 10);

    // 自动关闭
    setTimeout(() => {
        notification.style.opacity = '0';
        notification.style.transform = 'translateY(-20px)';
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 5000);
}

// 设置按钮交互效果
function setupButtonInteractions() {
    const buttons = document.querySelectorAll('button, a[class^="btn-"]');
    buttons.forEach(button => {
        // 添加点击效果
        button.addEventListener('mousedown', function() {
            this.style.transform = 'scale(0.96)';
            this.style.boxShadow = '0 2px 8px rgba(0, 0, 0, 0.15)';
        });

        button.addEventListener('mouseup', function() {
            this.style.transform = 'scale(1)';
            this.style.boxShadow = '';
        });

        button.addEventListener('mouseleave', function() {
            this.style.transform = 'scale(1)';
            this.style.boxShadow = '';
        });

        // 添加删除确认对话框
        if (button.classList.contains('btn-delete')) {
            button.addEventListener('click', function(e) {
                if (!confirm('确定要删除这条记录吗？此操作不可撤销。')) {
                    e.preventDefault();
                }
            });
        }
    });
}

// 设置表格行悬停效果
function setupTableHoverEffects() {
    const tableRows = document.querySelectorAll('.employee-table tbody tr');
    tableRows.forEach(row => {
        row.addEventListener('mouseenter', function() {
            this.style.backgroundColor = '#f8f9fa';
            this.style.transform = 'scale(1.005)';
            this.style.boxShadow = '0 4px 15px rgba(0, 0, 0, 0.05)';
            this.style.transition = 'all 0.3s ease';
        });

        row.addEventListener('mouseleave', function() {
            this.style.backgroundColor = '';
            this.style.transform = 'scale(1)';
            this.style.boxShadow = '';
        });
    });
}

// 设置平滑滚动
function setupSmoothScroll() {
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function(e) {
            e.preventDefault();

            const targetId = this.getAttribute('href');
            const targetElement = document.querySelector(targetId);

            if (targetElement) {
                window.scrollTo({
                    top: targetElement.offsetTop - 80, // 减去头部高度
                    behavior: 'smooth'
                });
            }
        });
    });
}

// 为导航栏设置当前活动项
function setActiveNavItem() {
    const currentPath = window.location.pathname;
    const navLinks = document.querySelectorAll('nav ul li a');

    navLinks.forEach(link => {
        // 移除所有活动状态
        link.classList.remove('active');

        // 检查当前路径是否匹配链接路径
        const linkPath = link.getAttribute('href').split('?')[0]; // 去除查询参数

        if (linkPath === currentPath ||
            (currentPath.includes('/employee') && linkPath.includes('/employee')) ||
            (currentPath.includes('dashboard.jsp') && linkPath.includes('dashboard.jsp'))) {
            link.classList.add('active');
        }
    });
}

// 搜索表单重置功能增强
function enhanceSearchForm() {
    const resetButtons = document.querySelectorAll('.btn-reset');
    resetButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            const form = this.closest('form');
            if (form) {
                // 清空所有输入字段
                const inputs = form.querySelectorAll('input, select');
                inputs.forEach(input => {
                    input.value = '';
                    removeHighlight(input);
                });

                // 添加重置动画
                form.classList.add('reset-animation');
                setTimeout(() => {
                    form.classList.remove('reset-animation');
                }, 300);
            }
        });
    });
}

// 添加工具提示功能
function addTooltips() {
    const tooltipElements = document.querySelectorAll('.tooltip');
    tooltipElements.forEach(element => {
        const tooltipText = element.getAttribute('data-tooltip');
        if (tooltipText) {
            const tooltipSpan = document.createElement('span');
            tooltipSpan.classList.add('tooltiptext');
            tooltipSpan.textContent = tooltipText;
            element.appendChild(tooltipSpan);
        }
    });
}

// 添加表单输入动画
function setupFormInputAnimations() {
    const formGroups = document.querySelectorAll('.form-group');
    formGroups.forEach((group, index) => {
        // 延迟动画以创建序列效果
        setTimeout(() => {
            group.style.opacity = '1';
            group.style.transform = 'translateY(0)';
        }, 100 * index);
    });
}

// 添加页面元素进入动画
function setupElementAnimations() {
    const elements = document.querySelectorAll('.content-header, .form-container, .detail-container, .employee-table');
    elements.forEach((element, index) => {
        // 初始状态
        element.style.opacity = '0';
        element.style.transform = 'translateY(20px)';
        element.style.transition = 'all 0.5s ease-out';

        // 延迟动画以创建序列效果
        setTimeout(() => {
            element.style.opacity = '1';
            element.style.transform = 'translateY(0)';
        }, 200 * (index + 1));
    });
}

// 导出函数，以便在其他地方调用
window.setupFormValidations = setupFormValidations;
window.setupButtonInteractions = setupButtonInteractions;
window.setupTableHoverEffects = setupTableHoverEffects;
window.setupSmoothScroll = setupSmoothScroll;
window.setActiveNavItem = setActiveNavItem;
window.enhanceSearchForm = enhanceSearchForm;
window.addTooltips = addTooltips;
window.setupFormInputAnimations = setupFormInputAnimations;
window.setupElementAnimations = setupElementAnimations;
window.showNotification = showNotification;

// 添加自定义通知样式
const style = document.createElement('style');
style.textContent = `
    .custom-notification {
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 15px 20px;
        border-radius: 8px;
        color: white;
        font-weight: 500;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
        z-index: 10000;
        opacity: 0;
        transform: translateY(-20px);
        transition: all 0.3s ease;
        max-width: 300px;
        word-wrap: break-word;
    }
    
    .custom-notification.error {
        background: #f44336;
    }
    
    .custom-notification.success {
        background: #4caf50;
    }
    
    .custom-notification.info {
        background: #2196f3;
    }
    
    @keyframes shake {
        0%, 100% { transform: translateX(0); }
        10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
        20%, 40%, 60%, 80% { transform: translateX(5px); }
    }
    
    .reset-animation {
        animation: shake 0.5s ease-in-out;
    }
`;
document.head.appendChild(style);